<?php
/**
 * Created by PhpStorm.
 * User: warcello
 * Date: 2016/10/13
 * Time: 下午3:33
 */
class commune {
    public function communeIndex($param){
        $id = $param->id;
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $CommuneModel = M('community');
        Session::switchCustomer($cid);
        $result = $CommuneModel->where(array('id'=>$id,'deleted'=>0))->find();
        Output::instance()->module('commune','new')->objArray($result);
    }
    /**
     * 新增群
     * @param $groupname 群名称
     * @param $groupcount 群人数
     */
    public function communeGroupAdd($gid,$groupname,$groupcount){

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $CommuneModel = M('community');
        Session::switchCustomer($cid);
        $userName = Session::$user['userName'];
        if ($userName == '') {
            Output::instance()->resultCode(code_user_not_member);
            return false;
        }

        if($gid){
            $data["groupName"] =$groupname;
            $data["countNumber"] =$groupcount;
            $data["updateTime"] = date("Y-m-d H:i:s");
            $result = $CommuneModel->where(array('id'=>$gid,'userName'=>$userName))->save($data);
        }else{
            $data["groupName"] =$groupname;
            $data["countNumber"] =$groupcount;
            $data["customerId"] =$cid;
            $data["userName"] =$userName;
            $data["createTime"] = date("Y-m-d H:i:s");
            $data["updateTime"] = date("Y-m-d H:i:s");
            $result = $CommuneModel->add($data);
        }
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     * 社群详细信息
     * @param $id
     * @param $start
     * @param $limit
     * @param string $order
     * @param string $orderBy
     */
    public function communeGroupInfo($id)
    {
        $result = array();
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $CommuneModel = M('community');
        Session::switchCustomer($cid);
        //获取社群信息
        $groupInfo = $CommuneModel->field("id,groupName,countNumber,userName,group_figure,customerId,shareTime")
                    ->where(['id'=>$id,'deleted'=>0])->find();
        $userName = Session::$user['userName'];
        if($userName != $groupInfo['userName']){
            Output::instance()->resultCode(code_user_priv_invalid);
            return;
        }
        array_push($result,$groupInfo);
        //获取排行榜列表和当前名次
        $str = "select * from (select id,group_figure,groupName,"
            ."(@rowNum:=@rowNum+1) as rowNo from wx_community,"
            ."(select (@rowNum :=0) ) b where deleted = 0"
            ." order by wx_community.group_figure desc ) u where u.id=".$id  ;
        $rowNum =$CommuneModel->query($str);
        $result[0]['myrank'] =$rowNum[0]['rowNo']?$rowNum[0]['rowNo']:0;
        Output::instance()->module('commune','info')->objArray($result);
    }


    /**
     * 社群列表页面
     */
    public function communeGroupView()
    {
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $miyouquan = M("miyouquan");
        Session::switchCustomer($cid);
        $Partner = $miyouquan->alias("a")
            ->join("inner join wx_quan_user c on a.id=c.qid")
            ->where("a.cId=$cid and c.status=1 and c.deleted=0 and c.uid=".Session::$user['userId'])
            ->find();

        if(!$Partner){
            Output::instance()->resultCode(code_user_priv_invalid);
            return;
        }else{
            Output::instance()->module('commune','my')->object();
        }
    }
    /**
     * 社群列表
     * @param $start
     * @param $limit
     * @param string $order
     * @param string $orderBy
     */
    public function communeGroupList($start, $limit,$order="updateTime", $orderBy="desc")
    {
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $CommuneModel = M('community');
        $miyouquan = M("miyouquan");
        Session::switchCustomer($cid);
        $Partner = $miyouquan->alias("a")
            ->join("inner join wx_quan_user c on a.id=c.qid")
            ->where("a.cId=$cid and c.status=1 and c.deleted=0 and c.uid=".Session::$user['userId'])
            ->find();

        if(!$Partner){
            Output::instance()->resultCode(code_user_priv_invalid);
            return;
        }
        $condition['customerId'] = $cid;
        $condition['deleted'] = 0;
        $condition['userName'] = Session::$user['userName'];
        $result = $CommuneModel->field('id,groupName,countNumber,userName,updateTime')
            ->where($condition)
            ->limit($start,$limit)
            ->order("$order $orderBy")
            ->select();
        $count =$CommuneModel->field('id,groupName,countNumber,userName,updateTime')
            ->where($condition)
            ->count();
        Output::instance()->objArray($result,$count);

    }

    /**
     * 活跃用户
     * @param $id
     * @param $start
     * @param $limit
     * @param string $order
     * @param string $orderBy
     */
    public function communeHotUserList($id,$start, $limit,$order="communityuser.clickTime", $orderBy="desc"){
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $CommuneUserModel = M('community_user');
        $CommuneModel = M('community');
        Session::switchCustomer($cid);
        $groupInfo = $CommuneModel->field("id,groupName,countNumber,userName,group_figure,customerId,shareTime")
            ->where(array('id'=>$id))->find();
        //获取活跃用户
        $condition['communityuser.groupId'] = array("eq",$id);
        $startTime = $groupInfo['shareTime'];
        $endTime=date('Y-m-d H:i:s',strtotime('+1 day ',strtotime($startTime)));
        $condition['communityuser.clickTime'] =  array(array('gt',$startTime),array('lt',$endTime)) ;
        $result =$CommuneUserModel->alias('communityuser')
            ->join('LEFT JOIN wx_'.$cid.'_user_weixin_info winfo on winfo.openid = communityuser.userName')
            ->join('LEFT JOIN wx_'.$cid.'_user u on u.userName = communityuser.userName' )
            ->where($condition)
            ->field('communityuser.*,winfo.headimgurl,winfo.nickname,winfo.subscribe,u.status')
            ->order($order,$orderBy)
            ->limit($start,$limit)
            ->group("communityuser.id")
            ->select();
        foreach ($result as $key =>$val){
            $result[$key]['tran_time'] = self::time_tran($val['clickTime'],$startTime);
            $result[$key]['listnum'] = $key+$start+1;

        }
        $count = $CommuneUserModel->alias('communityuser')
            ->join('LEFT JOIN wx_'.$cid.'_user_weixin_info winfo on winfo.openid = communityuser.userName')
            ->where($condition)
            ->count();

        if($result){
            Output::instance()->objArray($result,$count);
        }else{
            $result =array('code'=>0);
            Output::instance()->objArray($result,0);
        }


    }

    //排行榜
    public function comuneRankList($start,$limit){
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $CommuneModel = M('community');
        Session::switchCustomer($cid);
        $rstart =$start?$start:0;
        $rlimit =$limit?$limit:10;
        $top = $rstart-1<0?0:$rstart;

        $str = "select id,group_figure,groupName,"
            ."(@rowNum:=@rowNum+1) as rowNo from wx_community,"
            ."(select (@rowNum := $top) ) b  where deleted = 0  order by wx_community.group_figure desc limit $rstart,$rlimit ";
        $result = $CommuneModel->query($str);
        $count = $CommuneModel->where(['deleted'=>0])->count('id');
        Output::instance()->module('commune','num')->objArray($result,$count);
    }

    //签到
    public function communeSign($gid){
        $cid = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        Session::switchCustomer(0);
        $CommuneModel = M('community');
        $miyouquan = M('miyouquan');
        $CommuneUserModel = M('community_user');
        Session::switchCustomer($cid);
        $User = M('user');
        //判断是否是微信用户
        $userName = Session::$user['userName'];
        if(!$userName){
            Output::instance()->resultCode(code_user_not_exist);

            return;
        }

        //获取群信息
        $findGroupInfo = $CommuneModel->where(['id'=>$gid,'deleted'=>0])->find();
        if(!$findGroupInfo){
            Output::instance()->resultCode(-1,"社群不存在");
            return ;
        }
        $nowTime = date('Y-m-d H:i:s',time());
        $endTime = date('Y-m-d H:i:s',strtotime('+1 day ',strtotime($findGroupInfo['shareTime'])));
        $findGroupInfo['endTime']=$endTime;
        //判断分享状态
        if($findGroupInfo['shareTime']){
            if($endTime<$nowTime){
                $status=2;//0-未开始 1-进行中 2-已结束
            }else{
                $status=1;//0-未开始 1-进行中 2-已结束
            }

        }else{
            $status = 0; //0-未开始 1-进行中 2-已结束
        }
        $findGroupInfo['status']=$status;

        //时间差
        $thetime = date('H:i:s',strtotime($endTime)-(time()+8*3600+1));
        $findGroupInfo['thetime']=$thetime;
        //获取用户签到状态
        $sign=0; //0-未签到 1-已签到
        $findUser=$CommuneUserModel->where(['groupId'=>$gid,'userName'=>$userName])->find();
        if($findUser && $findUser['clickTime']>$findGroupInfo['shareTime'] && $findUser['clickTime']<$endTime && $nowTime<$endTime){
            $sign=1;

        }
        $findGroupInfo['clickTime']=self::time_tran($findUser['clickTime'],$findGroupInfo['shareTime']);
        $findGroupInfo['sign']=$sign;


        //获取用户信息
        $userinfo =$User->alias('u')
            ->join('LEFT JOIN wx_'.$cid.'_user_weixin_info uinfo on uinfo.openid = u.userName' )
            ->where(['u.userName'=>$userName])
            ->field('uinfo.nickname,u.status,uinfo.headimgurl')
            ->find();
        //若未关注返回二维码id
        if($userinfo['status'] =='sharesubscribe' || $userinfo['status']=='unsubscribe'){
            //获取用户分享id
            $qr = $miyouquan->alias('m')
                ->where(['m.cId'=>$cid])
                ->field('m.id')
                ->select();
            $findGroupInfo['qr_id']=$qr[0]['id'];
            $findGroupInfo['qr_uid']=$uid;
        }else{
            $findGroupInfo['nickname']=$userinfo['nickname'];
            $findGroupInfo['headimgurl']=$userinfo['headimgurl'];

        }
        //查找公众号名称
        $wechat = M('module_mall_store')->where(['cId'=>$cid])->find();
        $findGroupInfo['qr_name']=$wechat['name'];
        $conditions['groupId'] =$gid;
        $gettime =$findGroupInfo['shareTime'];
        $conditions['clickTime'] =array('gt',$gettime);
        $userRank = $CommuneUserModel->where($conditions)
                ->order("clickTime asc")
                ->getField("userName",true);
        if($userRank){
            $ranking= array_search($userName,$userRank)+1;
        }else{
            $ranking=0;
        }
        $findGroupInfo['ranking']=$ranking;
        $findGroupInfo['subscribe']=$userinfo['status'];

        Output::instance()->module('commune','share')->objArray($findGroupInfo);

    }

    /**
     * 点击签到接口
     * @param $gid
     */
    public function communeShareView($gid){

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $CommuneUserModel = M('community_user');
        $CommuneModel = M('community');
        Session::switchCustomer($cid);
        //判断是否是微信用户
        $userName = Session::$user['userName'];
        if(!$userName){
            Output::instance()->resultCode(code_user_not_exist);

            return;
        }
        //判断是否关注
        $WeixinUserInfo = M('user');
        $userinfo = $WeixinUserInfo->where(['userName'=>Session::$user['userName']])->find();
        $devote = 3;
        if($userinfo['status'] =='sharesubscribe' || $userinfo['status']=='unsubscribe'){
            $devote =1;
        }
        //更新点击时间
        $groupInfo = $CommuneModel->where(['id'=>$gid,'deleted'=>0])->find();
        $nowTime = date('Y-m-d H:i:s',time());
        $findUser = $CommuneUserModel->where(['groupId'=>$gid,'userName'=>$userName])->find();
        if($findUser){
            $endTime = date('Y-m-d H:i:s',strtotime('+1 day ',strtotime($groupInfo['shareTime'])));
            if($findUser['clickTime']<$groupInfo['shareTime'] && $findUser['clickTime']<$endTime && $nowTime<$endTime){
                $CommuneUserModel->where(['userName'=>$userName,'groupId'=>$gid])->save(['clickTime'=>$nowTime]);
                $CommuneModel->where(array('id'=>$gid))->setInc('group_figure',$devote);
                $CommuneModel->where(array('id'=>$gid))->setInc('hot_count');
            }

        }else{
            $data['clickTime'] = $nowTime;
            $data['createTime'] = $nowTime;
            $data['groupId'] = $gid;
            $data['userName'] = $userName;
            $CommuneUserModel->add($data);
            $CommuneModel->where(array('id'=>$gid))->setInc('group_figure',$devote);
            $CommuneModel->where(array('id'=>$gid))->setInc('hot_count');
        }

        //获取用户排名
        $gettime =$groupInfo['shareTime'];
        $conditions['groupId'] =$gid;
        $conditions['clickTime'] =array('gt',$gettime);
        $userRank = $CommuneUserModel->where($conditions)
            ->order("clickTime asc")
            ->getField("userName",true);
        if($userRank){
            $ranking= array_search($userName,$userRank)+1;
        }else{
            $ranking=0;
        }
        $result = $CommuneUserModel->where(['groupId'=>$gid,'userName'=>$userName])->find();
        $result['ranking']=$ranking;
        $result['clickTime'] = self::time_tran($result['clickTime'],$gettime);
        Output::instance()->objArray($result);
    }

    /**
     * 微信回调更新分享时间
     * @param $gid
     * @param $sharetime
     */

    public function updateShareTime($gid){

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $CommuneModel = M('community');
        Session::switchCustomer($cid);
        $sharetime = date('Y-m-d H:i:s',time());

        //判断是否是微信用户
        $userName = Session::$user['userName'];
        if(!$userName){
            Output::instance()->resultCode(code_user_not_exist);

            return;
        }
        $communegroup = $CommuneModel->where(['id'=>$gid,'deleted'=>0])->find();

        if($communegroup['userName']==$userName){
            $endTime = date('Y-m-d H:i:s',strtotime('+1 day ',strtotime($communegroup['shareTime'])));
            if($communegroup['shareTime'] == NULL || $sharetime> $endTime) {

                $data['shareTime'] = $sharetime;
                $data['group_figure'] = 0;
                $data['hot_count'] = 0;
                $CommuneModel->where(['id' => $gid])->save($data);
            }
        }
        //更新时间
        Output::instance()->resultCode();
    }

    /**
     * 群组删除功能
     * @param $gid
     */
    public function communeDeleteGroup($gid){

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $CommuneModel = M('community');
        Session::switchCustomer($cid);

        //判断用户是否存在
        $userName = Session::$user['userName'];
        if(!$userName){
            Output::instance()->resultCode(code_user_not_exist);

            return;
        }
        $communegroup = $CommuneModel->where(['id'=>$gid])->find();
        if($userName == $communegroup['userName']){
            $deletGroup = $CommuneModel->where(['id'=>$gid,'userName'=>$userName])->save(['deleted'=>1]);
            if($deletGroup){
                Output::instance()->resultCode();
            }else{
                Output::instance()->resultCode(code_sql_error);
            }
        }else{
            Output::instance()->resultCode(code_user_priv_invalid);
        }


    }



    //格式化时间
    public function time_tran($the_time,$startTime){
        $startTime = strtotime($startTime);
        $show_time = strtotime($the_time);
        $dur = $show_time - $startTime;
        if($dur < 0){
            return 0;
        }else{
            if($dur < 60){
                return $dur.'秒';
            }else{
                if($dur < 3600){
                    return floor($dur/60).'分钟'.floor($dur%60).'秒';
                }else{
                    if($dur < 86400){
                        return floor($dur/3600).'小时'.floor(($dur%3600)/60) .'分钟';
                    }else{
                        if($dur < 259200){//3天内
                            return floor($dur/86400).'天'.floor($dur%86400/3600).'小时';
                        }else{
                            return $the_time;
                        }
                    }
                }
            }
        }
    }


}